package cn.org.mrliu.ssm.qq;

import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import cn.org.mrliu.ssm.qq.config.QQConfig;
import cn.org.mrliu.ssm.qq.config.QQConfigUtil;

/**
 * QQ消息发送器
 * 
 * @author MrLiu
 *
 */
public class QQMessageSender {
	private static final Logger log = LoggerFactory.getLogger(QQMessageSender.class);
	private final static OkHttpClient client = new OkHttpClient();
	private static QQConfig config = QQConfigUtil.getConfig();
	private static String qqApi = config.getQqApi();
	private static Integer connectTimeout = config.getConnectTimeout();
	private static Integer readTimeout = config.getReadTimeout();
	private static final String ENCODING = QQConfigUtil.getConfig().getEncoding();

	static {
		// okhttp默认的连接超时为10秒
		client.setConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
		// okhttp默认的读取超时为10秒
		client.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS);
	}

	/**
	 * 通过Http请求发送QQ消息
	 * 
	 * @param qqMessage
	 */
	public static void send(QQMessage qqMessage) throws Exception {
		log.info("正在发送:" + qqMessage);
		// QQ消息类型
		String qqMessageType = qqMessage.getType();
		// QQ号码
		String qq = qqMessage.getQq();
		// QQ消息内容
		String message = qqMessage.getMessage();
		// QQ回调函数
		QQMessageCallback qqMessageCallback = qqMessage.getQqMessageCallback();

		// 请求路径
		String url = null;
		// 判断发送是否成功
		boolean isSuccess = false;
		// 响应结果
		String responseResult = null;
		// 异常对象
		Exception exception = null;
		try {
			// 编码消息
			message = URLEncoder.encode(message, ENCODING);
			url = qqApi + "&a=%3C%26%26%3E" + qqMessageType + "%3C%26%3E" + qq + "%3C%26%3E" + message;
			log.info("url:" + url);
			// 获取响应对象
			Response response = get(url);
			// 获取响应字符串
			responseResult = response.body().string();
			log.info("responseResult:" + responseResult);
			// 如果响应成功
			if (response.isSuccessful()) {
				try {
					JSONObject jsonObject = JSON.parseObject(responseResult);
					String desc = jsonObject.getString("desc");
					if ("ok".equals(desc)) {
						isSuccess = true;
					}
				} catch (Exception e) {
					isSuccess = false;
					exception = e;
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			isSuccess = false;
			exception = e;
			log.error("消息发送异常");
			e.printStackTrace();
		}

		// 处理
		if (isSuccess) {
			log.debug("消息发送成功");
			if (qqMessageCallback != null) {
				qqMessageCallback.onSuccess(qqMessage, url, responseResult);
			}
		} else {
			log.debug("消息发送失败");
			if (qqMessageCallback != null) {
				exception = new Exception("发送QQ消息失败:" + responseResult);
				qqMessageCallback.onFailure(qqMessage, url, exception);
			}
			throw exception;
		}

	}

	public static Response get(String url) throws Exception {
		long startTime = System.currentTimeMillis();
		// 构建HTTP请求对象
		Request request = new Request.Builder().url(url).build();
		// 执行HTTP请求并获取响应对象
		Response response = client.newCall(request).execute();
		long endTime = System.currentTimeMillis();
		long diffTime = endTime - startTime;
		log.debug("Http Request耗时:" + diffTime);
		return response;
	}

}
